# -*- coding: utf-8 -*-
import sys
import MySQLdb as db
import pymongo

reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8')

# global param
env = 'dev'
wid = 0



# 数据库连接
def withConnection(f):
    conn = None
    client = None
    try:
        if env == 'prod':
            conn = db.connect(      # 线上
                host="db-master.kuaihaowei.domain",
                port=13476,
                user="khw-usr",
                passwd="g5agXQwFkp3fD9US",
                db="khw",
                connect_timeout=5,
                use_unicode=True,
                charset='utf8',
                init_command='SET NAMES UTF8'
            )
            client = pymongo.MongoClient('mongo.kuaihaowei.domain', 27017)
        else:
            conn = db.connect(      # 测试
                host="127.0.0.1",
                port=3306,
                user="root",
                passwd="root",
                db="test",
                connect_timeout=5,
                use_unicode=True,
                charset='utf8'
            )
            client = pymongo.MongoClient('127.0.0.1', 27017)

        cursor = conn.cursor()
        mongo = client.khw      # 选择db

        # 业务函数
        f(cursor, mongo)

        # 关闭连接
        cursor.close()
        client.close()
    finally:
        if conn:
            conn.commit()
            conn.close()
        if client:
            client.close()


def doWork(cursor, mongo):
    foodType = getFoodType(cursor)

    for name in foodType:
        res = mongo.foodStatReport.update_many(
            {'wid': long(wid), 'name': name},
            {'$set':
                {'type': foodType[name]}
            }
        )
        print wid, name, foodType[name], res.matched_count

def getFoodType(cursor):
    cursor.execute(
        "select food_name, food_type from foods_ticket_stat where wid = %s", (wid,))
    result = {}
    for row in cursor:
        result[row[0]] = row[1]

    return result


if __name__ == '__main__':
    global env, wid
    env = sys.argv[1]
    wid = sys.argv[2]
    print env, wid
    withConnection(doWork)
